package org.zhxy.core.system.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.zhxy.common.response.ProfileResult;
import org.zhxy.common.response.Result;
import org.zhxy.common.response.ResultCode;

import java.util.Map;

@RestController
@RequestMapping("/access")
public class LoginController {

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody Map<String,Object> loginMap){
        String username = loginMap.get("username").toString();
        String password = loginMap.get("password").toString();
        try {
            password = new Md5Hash(password,username,3).toString();
            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(upToken);
            String sessionId = (String)subject.getSession().getId();
            return new Result(ResultCode.SUCCESS_NO_MESSAGE,sessionId);
        }catch (Exception e) {
            return new Result(ResultCode.MOBILE_OR_PASSWORD_OR_TYPE_ERROR);
        }
    }

    @RequestMapping(value="/profile",method = RequestMethod.GET)
    public Result profile() throws Exception {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        ProfileResult result = (ProfileResult)principals.getPrimaryPrincipal();
        return new Result(ResultCode.SUCCESS_NO_MESSAGE,result);
    }
}
